<template>
  <div class="container">
    <div class="header-box">
      <van-nav-bar
          title="创建订单"
          left-text="返回"
          :right-text="saveForm.orderno != null ? '打单' : ''"
          left-arrow
          @click-left="onClickLeft"
          @click-right="showManager = true"
      />
    </div>
    <van-form @submit="onSubmit" @failed="errorSubmit" class="order-form">
      <!-- 订单号 -->
      <div class="form-item" v-if="saveForm.orderno">
        <p>
          <span>订单号</span>
          <span class="label-en">Order No</span>
        </p>
        <van-field
            v-model="saveForm.orderno"
            name="orderno"
            placeholder="订单号"
            readonly
        />
      </div>
      <!-- 入仓时间 -->
      <div class="form-item">
        <p>
          <span>入仓时间</span>
          <span class="label-en">Date of entry into warehouse</span>
        </p>
        <van-field
            readonly
            autocomplete="off"
            v-model="saveForm.warehousingTime"
            name="warehousingTime"
            placeholder="入仓时间"
            @click="selectDate"
        />
      </div>
      <!-- 客户名称 -->
      <div class="form-item" title="客户名称">
        <p>
          <span>客户名称</span>
          <span class="label-en">Customer's name</span>
        </p>
        <van-field
            autocomplete="off"
            v-model="saveForm.customerName"
            name="customerName"
            @blur="selectCustomerName"
            placeholder="请输入客户名称"
            :rules="[{ required: true, sas: '123123' }]"
        />
      </div>
      <!-- 客户代码 -->
      <div class="form-item" v-if="saveForm.customerCode != null">
        <p>
          <span>客户代码</span>
          <span class="label-en">Customer's code</span>
        </p>
        <van-field
            disabled
            autocomplete="off"
            v-model="saveForm.customerCode"
            name="customerCode"
            placeholder="客户代码"
        />
      </div>
      <!-- 客户电话 -->
      <div class="form-item" v-if="saveForm.customerCode != null">
        <p>
          <span>客户电话</span>
          <span class="label-en">Customer's phone</span>
        </p>
        <van-field
            :disabled="saveForm.customerId ? true : false"
            autocomplete="off"
            v-model="saveForm.customerPhone"
            name="customerPhone"
            placeholder="请输入客户电话"
        />
      </div>
      <!-- 客户国籍 -->
      <div class="form-item" v-if="saveForm.customerCode">
        <p>
          <span>客户国籍</span>
          <span class="label-en">Customer's nationality</span>
        </p>
        <van-field
            disabled
            v-if="saveForm.customerId"
            autocomplete="off"
            v-model="saveForm.nationalityName"
            name="nationalityName"
        />
        <van-field
            disabled
            @click="showCountry = true"
            v-if="!saveForm.customerId"
            autocomplete="off"
            v-model="saveForm.nationalityName"
            name="nationalityName"
            placeholder="请选择客户国籍"
        />
      </div>
      <!-- 货物名称 -->
      <div class="form-item">
        <p>
          <span>货物名称</span>
          <span class="label-en">Goods Name</span>
        </p>
        <van-field
            autocomplete="off"
            v-model="saveForm.goodsName"
            name="goodsName"
            placeholder="请输入货物名称"
            :rules="[{ required: true }]"
        />
      </div>
      <!-- 货物数量、包装数量、货物体积-->
      <van-row>
        <van-col span="12">
          <div class="form-item">
            <p>
              <span>包装数量</span>
              <span class="label-en">Package Quantity</span>
            </p>
            <van-field
                autocomplete="off"
                v-model="saveForm.packageNum"
                name="packageNum"
                type="number"
                oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>9999999)value=9999999;if(value<0)value=0"
                placeholder="请输入包装数量"
                :rules="[{ required: true }]"
            />
          </div>
        </van-col>
        <van-col span="12">
          <div class="form-item">
            <p>
              <span>货物总数量</span>
              <span class="label-en">Cargo Quantity</span>
            </p>
            <van-field
                autocomplete="off"
                v-model="saveForm.total"
                name="total"
                type="number"
                oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>9999999)value=9999999;if(value<0)value=0"
                placeholder="请输入货物总数量"
                :rules="[{ required: true }]"
            />
          </div>
        </van-col>
      </van-row>
      <van-row>
        <van-col span="12">
          <div class="form-item">
            <p>
              <span>货物体积</span>
              <span class="label-en">Cargo Volume</span>
            </p>
            <van-field
                autocomplete="off"
                v-model="saveForm.goodsSize"
                name="goodsSize"
                type="number"
                maxlength="8"
                placeholder="请输入货物体积"
                oninput="value=value.match(/^\d+(?:\.\d{0,2})?/)"
            />
          </div>
        </van-col>
        <van-col span="12">
          <!-- 存放区号 -->
          <div class="form-item">
            <p>
              <span>存放区号</span>
              <span class="label-en">Storage area number</span>
            </p>
            <van-field
                autocomplete="off"
                v-model="saveForm.area"
                name="area"
                placeholder="请输入存放区号"
                :rules="[{ required: true }]"
            />
          </div>
        </van-col>
      </van-row>
      <!-- 档口地址 -->
      <div class="form-item">
        <p>
          <span>档口地址</span>
          <span class="label-en">Stall address</span>
        </p>
        <van-field
            autocomplete="off"
            v-model="saveForm.sellerAddress"
            name="sellerAddress"
            placeholder="请输入档口地址"
            :rules="[{ required: true }]"
        />
      </div>
      <!-- 档口电话 -->
      <div class="form-item">
        <p>
          <span>档口电话</span>
          <span class="label-en">Stall phone</span>
        </p>
        <van-field
            autocomplete="off"
            v-model="saveForm.sellerPhone"
            name="sellerPhone"
            placeholder="请输入档口电话"
            :rules="[{ required: true }]"
        />
      </div>
      <!-- 物流公司 -->
      <div class="form-item">
        <p>
          <span>物流公司</span>
          <span class="label-en">Logistics company</span>
        </p>
        <van-field
            readonly
            @click="showCompany = true"
            autocomplete="off"
            v-model="saveForm.companyName"
            name="companyName"
            placeholder="物流公司"
        />
      </div>
      <!-- 公司电话 -->
      <div class="form-item">
        <p>
          <span>公司电话</span>
          <span class="label-en">Logistics company phone</span>
        </p>
        <van-field
            readonly
            autocomplete="off"
            v-model="saveForm.companyPhone"
            name="companyPhone"
            placeholder="公司电话"
        />
      </div>
      <!-- 公司地址 -->
      <div class="form-item">
        <p>
          <span>公司地址</span>
          <span class="label-en">Logistics company address</span>
        </p>
        <van-field
            readonly
            v-model="saveForm.companyAddress"
            name="companyAddress"
            placeholder="公司地址"
        />
      </div>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">
          {{ saveForm.id == null ? "创建订单" : "更新订单" }}
        </van-button>
      </div>
    </van-form>
    <!-- 日期选择器 -->
    <van-popup v-model="dateShow" position="bottom">
      <van-datetime-picker
          @confirm="selectDataVal"
          @cancel="dateShow = false"
          v-model="currentDate"
          type="datetime"
          title="选择年月日"
      />
    </van-popup>
    <!-- 公司选择器 -->
    <van-popup v-model="showCompany" position="bottom">
      <van-picker
          title="选择物流公司"
          value-key="cname"
          show-toolbar
          :columns="companyList"
          @confirm="onConfirmCompany"
          @cancel="showCompany = false"
      />
    </van-popup>
    <!-- 国籍选择器 -->
    <van-popup v-model="showCountry" position="bottom">
      <van-picker
          title="请选择客户国籍"
          show-toolbar
          :columns="countryList"
          @confirm="onConfirmCountry"
          @cancel="showCountry = false"
      />
    </van-popup>
    <!-- 保存成功后页面 -->
    <van-popup
        v-model="showSuccess"
        :style="{ height: '100%' }"
        position="bottom"
    >
      <div class="save-success">
        <span
            style="text-align: center; padding-bottom: 10px; font-weight: 600"
        >
          留在当前页面可以将手机给仓管打单
        </span>
        <van-button block type="info" size="large" to="/">返回主页</van-button>
        <van-button block type="info" size="large" @click="showManagerPrint">
          仓管打单
        </van-button>
      </div>
    </van-popup>
    <!-- 仓管打单弹窗 -->
    <van-popup
        v-model="showManager"
        position="bottom"
        :style="{ height: '100%' }"
    >
      <div class="print-box">
        <van-field
            v-model="managerPrint.account"
            name="username"
            label="仓管工号"
            autocomplete="off"
            placeholder="请输入仓管工号"
            :rules="[{ required: true }]"
        />
        <van-field
            v-model="managerPrint.password"
            type="password"
            name="password"
            label="仓管密码"
            autocomplete="off"
            placeholder="请输入密码"
            :rules="[{ required: true }]"
        />
        <van-button block type="info" size="large" @click="printOrder"
        >打单
        </van-button>
        <van-button block type="info" size="large" @click="showManager = false"
        >取消
        </van-button>
      </div>
    </van-popup>
    <!-- 页面加载 -->
    <div class="page-loading" v-if="pageLoading">
      <van-loading color="#1989fa" text-color="#1989fa" vertical>
        加载中...
      </van-loading>
    </div>
    <van-popup v-model="showPrinterPicker" round position="bottom">
      <van-picker
          show-toolbar
          value-key="label"
          :columns="printerList"
          @cancel="showPrinterPicker = false"
          @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>

<script lang="ts">
import {Component, Vue} from "vue-property-decorator";
import tools from "@/utils/tools";

import {
  findCountry,
  findCompanyList,
  getCustomerInfo,
  createOrder,
  updateWhOrder,
  managerPrint, findPrinterList,
} from "@/api/system";
import {Notify, Toast} from "vant";
import {printOrder, printPackage} from "@/api/manager";

@Component({
  components: {},
})
export default class HomeView extends Vue {
  // 页面加载遮罩
  pageLoading = false;
  // 显示保存成功
  showSuccess = false;
  showManager = false;
  // 入仓日期
  dateShow = false;
  currentDate = "";
  // 物流公司
  showCompany = false;
  // 国籍选择器
  showCountry = false;
  // 公司列表
  companyList = [];
  // 获取国籍列表
  countryList = [];
  // 订单表单
  saveForm: any = {
    id: null,
    orderno: null,
    goodsName: "",
    goodsSize: "",
    packageNum: "",
    total: "",
    area: "",
    warehousingTime: tools.formatDate(new Date(), "yyyy-MM-dd HH:mm"),
    customerId: "",
    customerName: "",
    customerCode: null,
    customerPhone: null,
    nationality: "",
    nationalityName: "",
    sellerAddress: "",
    sellerPhone: "",
    companyId: "",
    companyName: "",
    companyPhone: "",
    companyAddress: "",
  };
  // 仓管
  managerPrint: any = {
    orderId: this.saveForm.id,
    account: null,
    password: null,
    printerDeviceId: null
  };
  // 打印机id
  printerList: any = [];
  showPrinterPicker = false;
  printerDeviceId: number = 0;

  // 日期选择器
  selectDate() {
    this.dateShow = true;
  }

  selectDataVal(val: any): void {
    this.saveForm.warehousingTime = tools.formatDate(val, "yyyy-MM-dd HH:mm");
    this.dateShow = false;
  }

  // 确定选择公司
  onConfirmCompany(val: any): void {
    this.saveForm.companyId = val.id;
    this.saveForm.companyName = val.cname;
    this.saveForm.companyPhone = val.phone;
    this.saveForm.companyAddress = val.address;
    this.showCompany = false;
  }

  // 选择客户国籍
  onConfirmCountry(val: any): void {
    this.saveForm.nationality = val.code;
    this.saveForm.nationalityName = val.text;
    this.showCountry = false;
  }

  // 获取公司列表
  async getCompanyList(): Promise<void> {
    this.companyList = (await findCompanyList()).data;
  }

  // 获取国籍列表
  async getCountryList(): Promise<void> {
    this.countryList = (await findCountry()).data;
  }

  // 查找用户名称
  async selectCustomerName(): Promise<void> {
    const customerName = this.saveForm.customerName;
    if (customerName.trim() != "") {
      try {
        this.pageLoading = true;
        const {data} = await getCustomerInfo(customerName.trim());
        this.saveForm.customerCode = data.code;
        this.saveForm.customerId = data.userId;
        this.saveForm.customerName = data.username;
        this.saveForm.customerPhone = data.phone;
        this.saveForm.nationality = data.nationalityId;
        this.saveForm.nationalityName = data.nationalityName;
        this.pageLoading = false;
      } catch (e: any) {
        this.pageLoading = false;
      }
    }
  }

  // 生命钩子
  async created(): Promise<void> {
    try {
      this.pageLoading = true;
      await this.getCompanyList();
      await this.getCountryList();
      // 选择公司
      for (let i = 0; i < this.companyList.length; i++) {
        if (this.$route.query.companyId == (this.companyList[i] as any).id) {
          this.saveForm.companyId = (this.companyList[i] as any).id;
          this.saveForm.companyName = (this.companyList[i] as any).cname;
          this.saveForm.companyPhone = (this.companyList[i] as any).phone;
          this.saveForm.companyAddress = (this.companyList[i] as any).address;
          break;
        }
      }
      this.pageLoading = false;
    } catch (e) {
      this.pageLoading = false;
    }
  }

  // 表单验证未通过
  errorSubmit(val: any): void {
    Notify({type: "warning", message: "请完善必填项"});
  }

  // 提交订单
  async onSubmit(): Promise<void> {
    try {
      this.pageLoading = true;
      if (this.saveForm.id == null) {
        const {data} = await createOrder(this.saveForm);
        Notify({type: "primary", message: "新增成功"});
        this.saveForm.id = data.id;
        this.saveForm.orderno = data.orderno;
        this.showSuccess = true;
      } else {
        await updateWhOrder(this.saveForm);
        Notify("更新成功");
        Notify({type: "primary", message: "更新成功"});
      }
      this.pageLoading = false;
    } catch (e) {
      Notify("操作失败");
      this.pageLoading = false;
    }
  }

  // 返回
  onClickLeft(): void {
    this.$router.push("/");
  }

  // 显示打单仓管打单
  showManagerPrint(): void {
    this.showSuccess = false;
    this.showManager = true;
  }

  // 获取打印机列表
  async getPrinterList(): Promise<void> {
    this.pageLoading = true
    try {
      const res = await findPrinterList()
      this.printerList = res.data
      this.pageLoading = false
    } catch (e: any) {
      this.pageLoading = false
      Toast(e?.message || "获取打印机列表失败")
    }
  }

  onConfirm(item: any): void {
    this.printerDeviceId = item.value
  }

  // 打单
  async printOrder(): Promise<void> {
    await this.getPrinterList()
    if (this.printerDeviceId == 0) {
      Toast("请选择打印机");
      return;
    }
    const username = this.managerPrint.account.trim();
    const password = this.managerPrint.password.trim();
    if (username == "") {
      Toast("请输入仓管工号");
    } else if (password == "") {
      Toast("请输入仓管密码");
    } else {
      this.managerPrint.orderId = this.saveForm.id;
      this.managerPrint.account = this.managerPrint.account.trim();
      this.managerPrint.password = this.managerPrint.password.trim();
      this.managerPrint.printerDeviceId = this.printerDeviceId;
      try {
        this.pageLoading = true;
        await managerPrint(this.managerPrint);
        Notify({type: "primary", message: "已加入打印队列"});
        this.managerPrint.account = "";
        this.managerPrint.password = "";
        this.showManager = false;
        this.pageLoading = false;
      } catch (e) {
        this.pageLoading = false;
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;

  .header-box {
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 99;
  }

  .order-form {
    position: absolute;
    top: 46px;

    .form-item {
      padding-top: 5px;

      p {
        margin-left: 16px;
        font-size: 16px;
        line-height: 20px;

        span {
          display: block;
        }

        .label-en {
          font-weight: 600;
          font-size: 14px;
        }
      }

      border-bottom: 1px #f5f5f5 solid;
    }
  }

  .save-success {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    box-sizing: border-box;
    padding: 20px;

    .van-button {
      margin-bottom: 10px;
    }
  }

  .print-box {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 10px;

    .van-button {
      margin-top: 10px;
    }
  }
}

.page-loading {
  position: fixed;
  top: 0;
  z-index: 99;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.3);
}
</style>
